package com.sands.utils;

import android.content.Context;
import android.os.Handler;


import com.sands.app.App;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public abstract class Toast {
    public static boolean debug_flag = true;

    public static final int LENGTH_SHORT = android.widget.Toast.LENGTH_SHORT;
    public static final int LENGTH_LONG = android.widget.Toast.LENGTH_LONG;

    private static android.widget.Toast toast;
    private static Handler handler = new Handler();

    private static Runnable run = new Runnable() {
        public void run() {
            toast.cancel();
        }
    };
    private static Context mContext;

    static {
        mContext = App.getInstance();
    }

    private static void toast(Context ctx, CharSequence msg, int duration) {
        handler.removeCallbacks(run);
        // handler的duration不能直接对应Toast的常量时长，在此针对Toast的常量相应定义时长
        switch (duration) {
            case LENGTH_SHORT:// Toast.LENGTH_SHORT值为0，对应的持续时间大概为1s
                duration = 2000;
                break;
            case LENGTH_LONG:// Toast.LENGTH_LONG值为1，对应的持续时间大概为3s
                duration = 4000;
                break;
            default:
                break;
        }
        if (null != toast) {
            toast.setText(msg);
        } else {
            toast = android.widget.Toast.makeText(ctx.getApplicationContext(), msg, duration);
        }
        handler.postDelayed(run, duration);
        toast.show();
    }

    /**
     * 弹出Toast
     *
     * @param ctx      弹出Toast的上下文
     * @param msg      弹出Toast的内容
     * @param duration 弹出Toast的持续时间
     */
    public static void show(CharSequence msg, int duration)
            throws NullPointerException {

        if (0 > duration) {
            duration = LENGTH_SHORT;
        }
        toast(mContext, msg, duration);
    }

    public static void debugShow(CharSequence msg, int duration) {
        if (!debug_flag) {
            return;
        }
        if (0 > duration) {
            duration = LENGTH_SHORT;
        }
        toast(mContext, msg, duration);
    }

    /**
     * 弹出Toast
     *
     * @param ctx      弹出Toast的上下文
     * @param msg      弹出Toast的内容的资源ID
     * @param duration 弹出Toast的持续时间
     */
    public static void show(int resId, int duration)
            throws NullPointerException {

        if (0 > duration) {
            duration = LENGTH_SHORT;
        }
        toast(mContext, mContext.getResources().getString(resId), duration);
    }


    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

}